import { _decorator, Component, director, game, screen, view, Vec2, ResolutionPolicy } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('AdaptiveScreen')
export class AdaptiveScreen extends Component {
    @property
    designWidth: number = 750;  // iPhone 设计宽度

    @property
    designHeight: number = 1334;  // iPhone 设计高度

    @property
    iPadDesignWidth: number = 1024;  // iPad 设计宽度

    @property
    iPadDesignHeight: number = 1366;  // iPad 设计高度

    onLoad() {
        this.initScreenAdapter();

        // 监听屏幕尺寸变化事件
        screen.on("window-resize", this.onScreenResize, this);
        screen.on("fullscreen-change", this.onScreenResize, this);
    }

    private initScreenAdapter() {
        // 设置默认设计分辨率
        view.setDesignResolutionSize(
            this.designWidth,
            this.designHeight,
            ResolutionPolicy.FIXED_WIDTH
        );
        this.adjustGameView();
    }

    private onScreenResize() {
        this.adjustGameView();
    }

    private adjustGameView() {
        const frameSize = screen.windowSize;
        const isIPad = this.isIPadResolution(frameSize.width, frameSize.height);

        // 根据设备类型设置不同的设计分辨率
        const designWidth = isIPad ? this.iPadDesignWidth : this.designWidth;
        const designHeight = isIPad ? this.iPadDesignHeight : this.designHeight;

        console.log("设计分辨率:", designWidth, designHeight, isIPad);

        // 设置设计分辨率
        view.setDesignResolutionSize(
            designWidth,
            designHeight,
            ResolutionPolicy.FIXED_WIDTH
        );

        // 计算缩放比例
        const scaleX = frameSize.width / designWidth;
        const scaleY = frameSize.height / designHeight;

        // 发送适配信息事件，其他组件可以监听此事件进行相应调整
        this.node.emit('screen-adapted', {
            isIPad,
            frameSize,
            designSize: { width: designWidth, height: designHeight },
            scale: { x: scaleX, y: scaleY }
        });
    }

    private isIPadResolution(width: number, height: number): boolean {
        // 判断是否为 iPad 分辨率（通常宽高比接近 4:3）
        const aspectRatio = width / height;
        return aspectRatio >= 0.7 && aspectRatio <= 0.8;
    }

    onDestroy() {
        screen.off("window-resize", this.onScreenResize, this);
        screen.off("fullscreen-change", this.onScreenResize, this);
    }
}